#include <stdio.h>
#include <avr\io.h>
#include <avr\interrupt.h>
#define cap_In1                  PB0     
#define cap_In2                 PB2
#define mPORT_cap                  PORTB

#define IS_SET(REG, BIT) ((REG & _BV(BIT)) != 0)
#define SET_BIT(REG, BIT) do {REG |= _BV(BIT);}while(0)
#define CLR_BIT(REG, BIT) do {REG &= ~_BV(BIT);}while(0)





// initializarea convertorului analog digital
void ADC_init()
{
	// AVCC cu condesator pe AREF; PA0 ca input single ended; rezultat left-adjusted (8 biti de date)
	ADMUX = (1<<REFS0) | (1<<ADLAR) ;
	// activeaza ADC si intreruperea de conversie. Prescaler de ceas la maximum
	ADCSRA = (1<<ADEN) | (1<<ADIE) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0);
}
 
// intreruperea de conversie



SIGNAL(SIG_ADC)
{
	int data, temp,i,j;
	data = ADCH;
	temp = data;
	if ((temp < 105) && (temp > 95))
	stop_head();
	if (temp <95)
	change_direction_head2();
	if ((temp >105) )
	change_direction_head1();
	int cifra = data/100 ;
	if (cifra != 0)
	PORTD = ~0;
}

void stop_head()
{
        
                CLR_BIT(mPORT_cap, cap_In1);
                CLR_BIT(mPORT_cap, cap_In2);
                
}

void change_direction_head2()
{


	CLR_BIT(mPORT_cap, cap_In1);
	SET_BIT(mPORT_cap, cap_In2);

}

void change_direction_head1()
{

	CLR_BIT(mPORT_cap, cap_In2);
	SET_BIT(mPORT_cap, cap_In1);
}





int main()
{
	OCR1A = 156;
	TCCR1A = 0;
	TCCR1B = (1<<WGM12)|(1<<CS12)|(1<<CS10);
	TIMSK |= _BV(OCIE1A);
	ADC_init();
	DDRB = ~0;
	PORTB = _BV(cap_In2);//motor cuplat in partea de sus- aceeasi treaba si pt cel de jos
	DDRD = ~0;
    PORTD = 0;
	sei();
	
	for(;;)
	{
		// cer ADC-ului sa faca o conversie
		ADCSRA |= (1<<ADSC);
	}
	return 0;
}


